/**
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 **/
package com.mbfasttrack.service;

import com.mbfasttrack.model.Action;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Marco Berri marcoberri@gmail.com http://tecnicume.blogspot.com
 */
@Service("ActionService")
@Transactional
public class ActionService extends Base {

    /**
     * 
     * @param fromobj 
     * @param username
     * @param toobj 
     * @return
     */
    public Action add(String username, com.mbfasttrack.model.Base fromobj, com.mbfasttrack.model.Base toobj) {

        //salvo l'azione per lo sream
        Action a = new Action();
        a.setObject(fromobj);

        a.setObjectname(fromobj.getClass().getSimpleName());
        if (toobj != null) {
            a.setTarget(toobj);
            a.setTargetname(toobj.getClass().getSimpleName());
        }
        a.setUser(userRepository.findOneByUsername(username));

        return actionRepository.save(a);


    }

    public Action add(String username, com.mbfasttrack.model.Base fromobj) {

        return add(username, fromobj, null);
    }

    /**
     * 
     * @param id 
     * @return
     */
    public List<Action> getAllByUserId(String id) {

        Query q = new Query(
                Criteria.where("user.$id").is(new ObjectId(id))).limit(10);


        q.sort().on("dateSaved", Order.DESCENDING);


        //log.debug("Query: " + q.getQueryObject());

        return mongoTemplate.find(q, Action.class);

    }
}
